package com.hawk.eye.client.config;

import com.hawk.eye.client.toolkit.*;
import com.hawk.eye.client.tracer.FeignRequestInterceptor;
import com.hawk.eye.client.tracer.TrackerFilter;
import feign.RequestInterceptor;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

import javax.servlet.DispatcherType;

/**
 * @className: HawkEyeClientConfiguration
 * @description: HawkEyeClient配置类
 * @author: salad
 * @date: 2023/10/9
 **/
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(HawkEyeProperties.class)
public class HawkEyeClientConfiguration {

    /**
     * 链路ID生成器
     *
     * @return 链路ID生成器
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(value = HawkEyeProperties.PREFIX + ".enabled", havingValue = "true")
    public TraceIdGenerator traceIdGenerator() {
        return new DefaultTraceIdGenerator();
    }

    /**
     * 链路属性的过滤器
     *
     * @param traceIdGenerator 链路ID生成器
     * @param environment
     * @return 链路属性的过滤器
     */
    @Bean("logTraceFilterRegistration")
    @ConditionalOnMissingBean(name = "trackerFilter")
    @ConditionalOnProperty(value = HawkEyeProperties.PREFIX + ".enabled", havingValue = "true")
    public FilterRegistrationBean<TrackerFilter> logTraceFilterRegistration(TraceIdGenerator traceIdGenerator, Environment environment) {
        FilterRegistrationBean<TrackerFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new TrackerFilter(traceIdGenerator, environment));
        registration.addUrlPatterns("/*");
        registration.setName("trackerFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registration;
    }

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(value = RequestInterceptor.class)
    public static class FeignRequestInterceptorConfiguration {

        @Bean("feignRequestInterceptor")
        public FeignRequestInterceptor feignRequestInterceptor() {
            return new FeignRequestInterceptor();
        }

    }

}
